package command

import (
	"context"
	"os/exec"
	"strings"
	"time"

	"atomgit.com/openlinksaas/gitwrap/utils"
	"github.com/spf13/cobra"
)

type CheckResult struct {
	HasGit          bool `json:"hasGit"`
	HasConfigGit    bool `json:"hasConfigGit"`
	HasGitLfs       bool `json:"hasGitLfs"`
	HasConfigGitLfs bool `json:"hasConfigGitLfs"`
}

var CheckCmd = &cobra.Command{
	Use: "check",
	Run: func(cmd *cobra.Command, args []string) {
		ctx, cancel := context.WithTimeout(cmd.Context(), 30*time.Second)
		defer cancel()

		result := &CheckResult{}
		//检查git命令是否存在
		gitPath, err := exec.LookPath("git")
		if err != nil {
			utils.OutputData(result)
			return
		}
		result.HasGit = true
		//检查git用户是否配置
		cfgData, err := exec.CommandContext(ctx, gitPath, "config", "--list", "--global").Output()
		if err != nil {
			utils.OutputData(result)
			return
		}
		hasUserEmail := false
		hasUserName := false
		hasLfsClean := false
		hasLfsSmudge := false
		hasLfsProcess := false
		for _, line := range strings.Split(string(cfgData), "\n") {
			line = strings.Trim(line, " \r\n\t")
			if strings.HasPrefix(line, "user.email=") {
				hasUserEmail = true
			} else if strings.HasPrefix(line, "user.name=") {
				hasUserName = true
			} else if strings.HasPrefix(line, "filter.lfs.clean=") {
				hasLfsClean = true
			} else if strings.HasPrefix(line, "filter.lfs.smudge=") {
				hasLfsSmudge = true
			} else if strings.HasPrefix(line, "filter.lfs.process=") {
				hasLfsProcess = true
			}
		}
		result.HasConfigGit = (hasUserEmail && hasUserName)
		//检查git-lfs是否存在
		_, err = exec.LookPath("git-lfs")
		if err == nil {
			result.HasGitLfs = true
		}
		//检查git-lfs是否配置
		result.HasConfigGitLfs = (hasLfsClean && hasLfsSmudge && hasLfsProcess)

		utils.OutputData(result)
	},
}
